package com.cmcc.aregister.ui.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.cmcc.aregister.MyApplication;
import com.cmcc.aregister.R;
import com.cmcc.aregister.cs.constant.Arguments;
import com.cmcc.aregister.cs.constant.ConfigUtilHelper;
import com.cmcc.aregister.cs.constant.GlobalSetting;
import com.cmcc.aregister.cs.http.HttpAsyncTask;
import com.cmcc.aregister.cs.model.Department;
import com.cmcc.aregister.cs.model.Doctor;
import com.cmcc.aregister.cs.util.PotoalParcelable;
import com.cmcc.aregister.cs.util.Utils;
import com.cmcc.aregister.ui.adapter.DepAdapter;

/**
 * 科室详情页
 */
public class DepartmentDetailActivity extends ParentActivity
{
    private static final String TAG = "DepartmentDetailActivity";
    // ------view------
    // private TextView doctor_list;
    private ListView doctorList;
    private ImageView attention_layout;
    private Button cancel_btn;
    private Button reserve_btn;

    // ------parameter------
    private Department department;
    private String attention;
    private int position;
    private String area_type;

    OnItemClickListener mOnItemClickListener = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int position,
            long arg3)
        {
            // TODO Auto-generated method stub
            Doctor doctor = department.doctor_list.get(position);
            Intent intent = null;
            Map<String, Object> httpMap = new HashMap<String, Object>();
            PotoalParcelable potoal = new PotoalParcelable(httpMap);
            intent = new Intent(DepartmentDetailActivity.this,
                DoctorDetailActivity.class);
            httpMap.put(Arguments.ACTIVITY_JUMP_DOCTOR, doctor);
            httpMap.put(Arguments.ACTIVITY_JUMP_AREA_TYPE, doctor.area_type);
            httpMap.put(Arguments.ACTIVITY_JUMP_POSITION, position);
            intent.putExtra(Arguments.INTENT_TO_NEXT_PAGE, potoal);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
    };

    // ------------

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        init(R.layout.p_dep_detail);
    }

    @Override
    protected void setupData()
    {
        Map<String, Object> httpMap = ((PotoalParcelable) getIntent()
            .getParcelableExtra(Arguments.INTENT_TO_NEXT_PAGE)).map;
        department = (Department) httpMap
            .get(Arguments.ACTIVITY_JUMP_DEPARTMENT);
        if (ConfigUtilHelper.debug)
        {
            Log.i(TAG, "---department---" + department);
        }
        position = (Integer) httpMap.get(Arguments.ACTIVITY_JUMP_POSITION);
        area_type = (String) httpMap.get(Arguments.ACTIVITY_JUMP_AREA_TYPE);
        if (ConfigUtilHelper.debug)
        {
            Log.i(TAG, "---department-area_type--" + area_type
                + "---dep_id-----" + department.dep_id);
        }
        sendGetDepartmentDetailTask(ConfigUtilHelper.getMobile(app), area_type,
            department.dep_id);
    }

    @Override
    protected void setupView()
    {
        ((ImageView) findViewById(R.id.title))
            .setBackgroundResource(R.drawable.department_detail_title);
        ((TextView) findViewById(R.id.name)).setText(department.dep_name);
        ((TextView) findViewById(R.id.hospital_name))
            .setText(department.unit_name);
        ((TextView) findViewById(R.id.level)).setText(department.key_level);
        attention_layout = (ImageView) findViewById(R.id.attention_layout);
        // doctor_list = (TextView) findViewById(R.id.doctor_list);
        doctorList = (ListView) findViewById(R.id.listview);
        doctorList.setOnItemClickListener(mOnItemClickListener);
        cancel_btn = (Button) findViewById(R.id.cancel_btn);
        reserve_btn = (Button) findViewById(R.id.reserve_btn);
        reserve_btn.setEnabled(false);
        // doctor_list.setMovementMethod(ScrollingMovementMethod.getInstance());
        ((TextView) findViewById(R.id.dep_desc))
            .setMovementMethod(ScrollingMovementMethod.getInstance());
        attention = MyApplication.getInstance().departmentMap
            .get(department.dep_id);
        if (attention == null || "".equals(attention))
        {
            attention = department.is_attention;
        }
        if ("1".equals(attention))
        {
            cancel_btn.setText(R.string.cancel_attention);
            attention_layout.setVisibility(View.VISIBLE);
            cancel_btn.setBackgroundResource(R.drawable.left_btn_cancel_bg);
        }
        else
        {
            cancel_btn.setText(R.string.confim_attention);
            attention_layout.setVisibility(View.GONE);
            cancel_btn.setBackgroundResource(R.drawable.left_btn_affirm_bg);
        }
        cancel_btn.setOnClickListener(onClickListener);
        reserve_btn.setOnClickListener(onClickListener);
    }

    // 跳转到登陆界面
    private void gotoLogin()
    {
        Intent intent = new Intent(DepartmentDetailActivity.this,
            UserLoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    OnClickListener onClickListener = new OnClickListener() {
        @Override
        public void onClick(View v)
        {
            int id = v.getId();
            if (id == R.id.cancel_btn)
            {
                if (!ConfigUtilHelper.isLogin(app))
                {
                    gotoLogin();
                    return;
                }
                else if ("1".equals(department.is_attention))
                {
                    sendCancelAttentionTask(ConfigUtilHelper.getMobile(app),
                        "1", area_type, department.dep_id);
                }
                else
                {
                    sendConfirmAttentionTask(ConfigUtilHelper.getMobile(app),
                        "1", area_type, department.dep_id);
                }
            }
            else if (id == R.id.reserve_btn)
            {
                if (!ConfigUtilHelper.isLogin(app))
                {
                    gotoLogin();
                    return;
                }
                if ("0".equals(department.area_type)
                    && ("null".equals(department.left_num) || "0"
                        .equals(department.left_num)))
                {

                    showSingleAlertDlg(getString(R.string.notice),
                        getString(R.string.no_left_num),
                        getString(R.string.close));
                }
                else
                {
                    if (department.area_type.equals("1"))
                    {// 异地
                        showSingleAlertDlg(getString(R.string.notice),
                            getString(R.string.no_left_num),
                            getString(R.string.close));
                        return;
                    }
                    // 儿童医院、遗传代谢科、生酮饮食科预约提醒 111是儿童医院的ID,3887表示遗传代谢科 6546代表生酮饮食科
                    if (department.unit_id.equals("111"))
                    {
                        if (department.dep_id.equals("3887"))
                        {
                            showAlertTipDlg(getString(R.string.notice),
                                getString(R.string.yichuan_tip),
                                getString(R.string.confirm),
                                getString(R.string.cancel));
                        }
                        else if (department.dep_id.equals("6546"))
                        {
                            showAlertTipDlg(getString(R.string.notice),
                                getString(R.string.shengtong_tip),
                                getString(R.string.confirm),
                                getString(R.string.cancel));
                        }
                        else
                        {
                            gotoAppointment();
                        }
                    }
                    else
                    {
                        gotoAppointment();
                    }
                }
            }
        }

    };

    /**
     * 转跳预约界面
     */
    private void gotoAppointment()
    {
        Intent intent = new Intent(DepartmentDetailActivity.this,
            AppointmentActivity.class);
        Map<String, Object> httpMap = new HashMap<String, Object>();
        PotoalParcelable potoal = new PotoalParcelable(httpMap);
        intent.putExtra(Arguments.ACTIVITY_JUMP_SCREENING_TYPE, 1);
        httpMap.put(Arguments.ACTIVITY_JUMP_UNIT_ID, department.unit_id);
        httpMap.put(Arguments.ACTIVITY_JUMP_CHOICE_HOSPITAL,
            department.unit_name);
        httpMap.put(Arguments.ACTIVITY_JUMP_DEP_ID, department.dep_id);
        httpMap.put(Arguments.ACTIVITY_JUMP_CHOICE_DEPARTMENT,
            department.dep_name);
        httpMap.put(Arguments.ACTIVITY_JUMP_AREA_TYPE, department.area_type);
        intent.putExtra(Arguments.INTENT_TO_NEXT_PAGE, potoal);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        if (ConfigUtilHelper.debug)
        {
            Log.i(TAG, "------科室对应医院名称------" + department.unit_name);
        }
        startActivity(intent);
    }

    public void showAlertTipDlg(String title, String msg, String posTitle,
        String nagativeTitle)
    {
        new AlertDialog.Builder(this)
            .setTitle(title)
            .setMessage(msg)
            .setIcon(android.R.drawable.ic_dialog_info)
            .setCancelable(true)
            .setPositiveButton(posTitle, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which)
                {
                    gotoAppointment();
                }
            })
            .setNegativeButton(nagativeTitle,
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {

                    }
                }).create().show();
    }

    ArrayList<String> docListStr = new ArrayList<String>();
    private DepAdapter mDepAdapter;

    public void setView()
    {
        if (ConfigUtilHelper.debug)
        {
            Log.i(TAG, "-setView--department--" + department);
        }
        ((TextView) findViewById(R.id.dep_desc)).setText(department.dep_intro);
        // StringBuffer sb = new StringBuffer();
        for (Doctor doctor : department.doctor_list)
        {
            // sb.append(doctor.doctor_name + "\n");
            docListStr.add(doctor.doctor_name);
        }
        if (department.doctor_list == null
            || department.doctor_list.size() == 0
            || department.area_type.equals("1"))
        {
            docListStr.add(getString(R.string.no_data));
            doctorList.setSelector(android.R.color.transparent);
            doctorList.setOnItemClickListener(null);
            reserve_btn.setEnabled(false);
        }
        else
        {
            reserve_btn.setEnabled(true);
        }
        mDepAdapter = new DepAdapter(this, docListStr);
        doctorList.setAdapter(mDepAdapter);
    }

    /**
     * 获取科室信息
     */
    private HttpAsyncTask sendGetDepartmentDetailTask;

    /**
     * 
     * @param mobile 手机号码 如果为空，则不处理关注相关数据
     * @param area_type 区域类别 0：本地 1：异地
     * @param dep_id 科室id
     */
    private void sendGetDepartmentDetailTask(String mobile, String area_type,
        String dep_id)
    {
        Map<String, String> parameterMap = new HashMap<String, String>();
        parameterMap.put("area_type", area_type);
        parameterMap.put("mobile", mobile);
        parameterMap.put("dep_id", dep_id);
        String getDepartmentDetailUrl = Utils.changeUrl(
            Arguments.SERVER_URL_GET_DEPARTMENT_DETAIL, parameterMap);
        if (ConfigUtilHelper.debug)
        {
            Log.i(TAG, "获取科室详情url:" + getDepartmentDetailUrl);
        }
        sendGetDepartmentDetailTask = new HttpAsyncTask(HttpAsyncTask.GET,
            GlobalSetting.XML_DEPARTMENT_DETAIL, getDepartmentDetailUrl,
            HttpAsyncTask.CACHE_TYPE_ACTION, false);
        showProgressDialog();
        sendGetDepartmentDetailTask
            .setUIHandler(sendGetDepartmentDetailTaskHandler);
        mHttpManager.execute(sendGetDepartmentDetailTask);
    }

    @SuppressWarnings("unchecked")
    Handler sendGetDepartmentDetailTaskHandler = new Handler() {
        public void handleMessage(Message msg)
        {
            logger.d("----------sendGetDepartmentDetailTaskHandler----------");
            switch (msg.what)
            {
            case HttpAsyncTask.TASK_NOTIFY_RETURN_DATA:
                dismissProgressDialog();
                if (msg.obj != null)
                {
                    try
                    {
                        Map<String, Object> httpMap = (Map<String, Object>) msg.obj;
                        Department department_1 = (Department) httpMap
                            .get(Arguments.XML_DEPARTMENT);
                        department.dep_intro = department_1.dep_intro;
                        department.doctor_list = department_1.doctor_list;
                        setView();
                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }
                else
                {
                    showSingleAlertDlg(getString(R.string.notice),
                        getString(R.string.read_fail),
                        getString(R.string.close));
                }
                break;
            case HttpAsyncTask.TASK_NOTIFY_CONNECTION_FAIL:
                dismissProgressDialog();
                showSingleAlertDlg(getString(R.string.notice),
                    getString(R.string.read_fail), getString(R.string.close));
                break;
            }
        }
    };

    /**
     * 我要关注
     */
    private HttpAsyncTask sendConfirmAttentionTask;

    /**
     * 
     * @param mobile 手机号码
     * @param attentionType 关注类别 N 0：关注医院1:关注科室2:关注医生
     * @param area_type 医院区域 N 0：本地 1是异地
     * @param id 相应id
     */
    private void sendConfirmAttentionTask(String mobile, String attentionType,
        String area_type, String id)
    {
        logger.d("----------sendConfirmAttentionTask----------");
        Map<String, String> parameterMap = new HashMap<String, String>();
        parameterMap.put("mobile", mobile);
        parameterMap.put("area_type", area_type);
        parameterMap.put("attentionType", "1");
        parameterMap.put("dep_id", id);
        String confirmAttentionUrl = Utils.changeUrl(
            Arguments.SERVER_URL_CONFIRM_ATTENTION, parameterMap);
        sendConfirmAttentionTask = new HttpAsyncTask(HttpAsyncTask.GET,
            GlobalSetting.XML_CONFIRM_ATTENTION, confirmAttentionUrl,
            HttpAsyncTask.CACHE_TYPE_ACTION, false);
        showProgressDialog();
        sendConfirmAttentionTask.setUIHandler(sendConfirmAttentionTaskHandler);
        mHttpManager.execute(sendConfirmAttentionTask);
    }

    @SuppressWarnings("unchecked")
    Handler sendConfirmAttentionTaskHandler = new Handler() {
        public void handleMessage(Message msg)
        {
            logger.d("----------sendConfirmAttentionTaskHandler----------");
            switch (msg.what)
            {
            case HttpAsyncTask.TASK_NOTIFY_RETURN_DATA:
                dismissProgressDialog();
                if (msg.obj != null)
                {
                    try
                    {
                        Map<String, Object> httpMap = (Map<String, Object>) msg.obj;
                        String status = (String) httpMap
                            .get(Arguments.XML_STATUS);
                        String message = (String) httpMap
                            .get(Arguments.XML_MESSAGE);
                        if ("0".equals(status))
                        {
                            attention_layout.setVisibility(View.VISIBLE);
                            cancel_btn.setText(R.string.cancel_attention);
                            cancel_btn
                                .setBackgroundResource(R.drawable.left_btn_cancel_bg);
                            department.is_attention = "1";
                        }

                        showSingleAlertDlg(getString(R.string.notice), message,
                            getString(R.string.close));
                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }
                else
                {
                    showSingleAlertDlg(getString(R.string.notice),
                        getString(R.string.attention_fail),
                        getString(R.string.close));
                }
                break;
            case HttpAsyncTask.TASK_NOTIFY_CONNECTION_FAIL:
                dismissProgressDialog();
                showSingleAlertDlg(getString(R.string.notice),
                    getString(R.string.read_fail), getString(R.string.close));
                break;
            }
        }
    };

    /**
     * 取消关注
     */
    private HttpAsyncTask sendCancelAttentionTask;

    /**
     * 
     * @param mobile 手机号码
     * @param attentionType 关注类别 N 0：关注医院1:关注科室2:关注医生
     * @param area_type area_type 区域ID Y 0是本地 1是异地 2是全部
     * @param id 相应id
     */
    private void sendCancelAttentionTask(String mobile, String attentionType,
        String area_type, String id)
    {
        logger.d("----------sendCancelAttentionTask----------");
        Map<String, String> parameterMap = new HashMap<String, String>();
        parameterMap.put("mobile", mobile);
        parameterMap.put("area_type", area_type);
        parameterMap.put("attentionType", "1");
        parameterMap.put("dep_id", id);
        String cancelAttentionUrl = Utils.changeUrl(
            Arguments.SERVER_URL_CANCEL_ATTENTION, parameterMap);
        sendCancelAttentionTask = new HttpAsyncTask(HttpAsyncTask.GET,
            GlobalSetting.XML_CANCEL_ATTENTION, cancelAttentionUrl,
            HttpAsyncTask.CACHE_TYPE_ACTION, false);
        showProgressDialog();
        sendCancelAttentionTask.setUIHandler(sendCancelAttentionTaskHandler);
        mHttpManager.execute(sendCancelAttentionTask);
    }

    @SuppressWarnings("unchecked")
    Handler sendCancelAttentionTaskHandler = new Handler() {
        public void handleMessage(Message msg)
        {
            logger.d("----------sendCancelAttentionTaskHandler----------");
            switch (msg.what)
            {
            case HttpAsyncTask.TASK_NOTIFY_RETURN_DATA:
                dismissProgressDialog();
                if (msg.obj != null)
                {
                    try
                    {
                        Map<String, Object> httpMap = (Map<String, Object>) msg.obj;
                        String status = (String) httpMap
                            .get(Arguments.XML_STATUS);
                        String message = (String) httpMap
                            .get(Arguments.XML_MESSAGE);
                        if ("0".equals(status))
                        {
                            attention_layout.setVisibility(View.GONE);
                            cancel_btn.setText(R.string.confim_attention);
                            cancel_btn
                                .setBackgroundResource(R.drawable.left_btn_affirm_bg);
                            department.is_attention = "0";
                        }

                        showSingleAlertDlg(getString(R.string.notice), message,
                            getString(R.string.close));

                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }
                else
                {

                    showSingleAlertDlg(getString(R.string.notice),
                        getString(R.string.cancel_fail),
                        getString(R.string.close));
                }
                break;
            case HttpAsyncTask.TASK_NOTIFY_CONNECTION_FAIL:
                dismissProgressDialog();
                showSingleAlertDlg(getString(R.string.notice),
                    getString(R.string.cancel_fail), getString(R.string.close));
                break;
            }
        }
    };

    @Override
    protected void setTaskHandlerNull()
    {
        if (sendGetDepartmentDetailTask != null)
        {
            sendGetDepartmentDetailTask.setTaskBindingHandler(null);
        }
        if (sendConfirmAttentionTask != null)
        {
            sendConfirmAttentionTask.setTaskBindingHandler(null);
        }
        if (sendCancelAttentionTask != null)
        {
            sendCancelAttentionTask.setTaskBindingHandler(null);
        }
    }

    @Override
    protected void onPause()
    {
        super.onPause();
        if (!department.is_attention.equals(attention))
        {
            app.changeAttention(1, department.dep_id, position,
                department.is_attention);
        }
    }
}